//initContainerHeight();
CURRENT_PAGE = 1;
TEMPLATE_SELF = '';
TEMPLATE_OTHER = '';
CHAT_OBJ = {};
MSG_OR_OFFER = 'offer';
CURRENT_AUCTION_GOODS = {id:0};
CURRENT_NUM = 0;
CURRENT_PRICE = 100;
PRICE_GAP = 10;
IS_OVER = false;
IS_HOST = false;
HAVE_BEGUN = 2;
COUNT_DOWN_ING = false;
$(function(){
	initData();
	//checkBail();
	//renderGrade();
	loadNextAuctionGoods();
	initEvent();
	initChat();
	USERNAME = $('#username').val();
});

function jumpToEditBail(){
	/*var shopId = $("#shopId").val();
	var url = "/editShop/"+shopId;*/
	var url = "/editShop";
	var r = $("#r").val();
	if(r)url += "?r="+r;
	window.location.href = url;
}

function initData(){
	//检查手机和支付密码
	var noPhone = $("#noPhone").val();
	if(noPhone){
		frontBaseConfirm("您还未绑定手机号码，是否前往绑定手机号码","jumpToBindUserPhone()",null);
	}
	var noPayPassword = $("#noPayPassword").val();
	if(noPayPassword){
		frontBaseConfirm("您还未设置支付密码，是否前往设置支付密码","jumpToPayPasswordFind()",null);
	}
	
	//检查保证金
	/*var creditMoneyLack = $("#creditMoneyLack").val();
	if(creditMoneyLack){
		var bail = $("#bail").val();
		var creditMoney = $("#creditMoney").val();
		if(!creditMoney)creditMoney = 0;
		var tip = '信誉保证金不足，无法出价。本次拍卖需要交纳的保证金为'+bail+'元，您当前交纳的信誉保证金为'+creditMoney+'元';
		lh.alert(tip);
	}*/
	
	HAVE_BEGUN = $('#haveBegun').val();//开始状态
	if(null == HAVE_BEGUN)HAVE_BEGUN = 1;
	var host = $('#host').val();
	if(host){
		IS_HOST = true;
		switchMsgOffer('msg');
		$('#hostCountdown').show();
	}
}

function renderGrade(){
	var grade = $('#instGrade').val();
	var gradeDom = '';
	if(grade && grade > 100){
		var grade = grade.toString();
		var diamond = grade[1];
		var star = grade[2];
		for(var j = 0;j<star;j++){
			gradeDom += '<img src="/images/front/sale_img2.png" width="12" height:"12" class="mgH1 fr" style="padding-top:2px;"/>';
		}
		for(var i = 0;i<diamond;i++){
			gradeDom += '<img src="/images/front/diamond_blue.png" width="15" height:"15" class="fr" style="padding-top:1px;"/>';
		}
	}
	$('#grade').append(gradeDom);
}

function loadNextAuctionGoods(){
	var auctionId = $('#auctionId').val();
	$.post('/getNextAuctionQuickGoods',{auctionId:auctionId},function(rsp){
		if(rsp.status == 'success'){
			var haveBegun = rsp.haveBegun;
			HAVE_BEGUN = haveBegun; 
			if(HAVE_BEGUN == 2){//拍卖中
				var seconds = rsp.remainSeconds;
				refreshTimmer(seconds);//成功加载拍品后就刷新倒计时
				countdownWithMask(auctionOneDone);//开始倒计时
			}else if(HAVE_BEGUN == 3){//拍卖结束
				auctionOver();
			}else if(HAVE_BEGUN == 1){//拍卖预展
				auctionPreCheck(auctionId);
			}
			CURRENT_NUM++;
			var auctionGoods = rsp.auctionQuickGoods;
			CURRENT_AUCTION_GOODS = auctionGoods;
			CURRENT_AUCTION_GOODS.total = rsp.total;
			CURRENT_AUCTION_GOODS.remain = rsp.remain;
			CURRENT_AUCTION_GOODS.deal = rsp.deal;
			CURRENT_PRICE = auctionGoods.offerPrice || auctionGoods.priceBegin;
			CURRENT_PRICE = parseInt(CURRENT_PRICE);
			freshGoodsDom();
		}else if(rsp.status == 'over'){//拍卖结束
			CURRENT_AUCTION_GOODS = null;
			auctionOver();
		}
	},'json');
}

function freshGoodsDom(){
	if(!CURRENT_AUCTION_GOODS.offerTimes)CURRENT_AUCTION_GOODS.offerTimes = 0;
	var goods = CURRENT_AUCTION_GOODS;
	$('#goodsRemain').text(goods.remain);
	$('#goodsDeal').text(goods.deal);
	$('#goodsTotal').text(goods.total);
	$('#picPath').attr('src',goods.picPath);
	$('#goodsName').text(goods.goodsName);
	$('#currentNum').text(CURRENT_NUM);
	var s = goods.goodsSerial;
	if(s){
		$('#goodsSerial').text(s);
		$('#serialSpan').show();
	}else{
		$('#serialSpan').hide();
	}
	$('#priceBegin').text(goods.priceBegin || 1);
	$('#currentPrice').text(CURRENT_PRICE || 1);
	$('#currentUser').text(goods.currentUser || '暂无');
	$('#offerTimes').text(goods.offerTimes || 0);
	$('#offerPrice').val(CURRENT_PRICE+PRICE_GAP);
	if(HAVE_BEGUN == 2){//在拍卖中时才发拍品描述
		var msgPrefixx = "第"+CURRENT_NUM+"件拍品："+goods.goodsName+"。   ";
		sendSystemMsg(false, msgPrefixx + goods.goodsDescription, 'msg_host', '主持人');
		sendSystemMsg(false, "大家开始出价吧", 'msg_host', '主持人');
	}
}

function initEvent(){
    $('#pf_host_cha').click(function () {
        $('#t_0100_17').hide();
        $(this).hide();
        $('#pf_host_cha2').show();
        initHallHeight();
    });
    $('#pf_host_cha2').click(function () {
        $('#t_0100_17').show();
        $(this).hide();
        $('#pf_host_cha').show();
        initHallHeight();
    });
}

function switchMsgOffer(operation){
	if(operation == 'offer'){
		if(IS_HOST){
			lh.alert('您是本拍场的主持人，不能参与竞价');return;
		}
		MSG_OR_OFFER = 'offer';
		$('#host_write').show();
		$('#host_sub').hide();
	}else{
		MSG_OR_OFFER = 'msg';
		$('#host_sub').show();
		$('#host_write').hide();
	}
}

function changePrice(operation){
	var offerPrice = $('#offerPrice').val();
	if(!offerPrice || !$.isNumeric(offerPrice))offerPrice = CURRENT_PRICE;
	offerPrice = parseInt(offerPrice);
	if(operation == 'add'){
		offerPrice = offerPrice + PRICE_GAP;
	}else if(operation == 'del'){
		offerPrice = offerPrice - PRICE_GAP;
	}
	if(offerPrice <= CURRENT_PRICE){
		offerPrice = CURRENT_PRICE + PRICE_GAP;
		lh.alert('不能低于当前出价');
	}
	$('#offerPrice').val(offerPrice);
	return offerPrice;
}

function changePriceGap(){
	if(CURRENT_PRICE <= 50){
		PRICE_GAP = 10;
	}else if(CURRENT_PRICE < 400){
		PRICE_GAP = 20;
	}else if(CURRENT_PRICE < 1000){
		PRICE_GAP = 50;
	}else{
		PRICE_GAP = 100;
	}
}

function initChat(){
	var chatGroupId = $('#chatGroupId').val();
	var userTokenId = $('#userTokenId').val();
	var userTokenPswd = $('#userTokenPswd').val();
	var chatSig = $('#sig').val();
	var chatTimeStamp = $('#timeStamp').val();
	var senderId = $('#senderId').val();
	var senderAvatar = $('#senderAvatar').val();
	var senderName = $('#senderName').val();
	var senderSerial = $('#senderSerial').val();

	/*var receiverTokenId = $('#receiverTokenId').val();
	var receiverId = $('#receiverId').val();
	var receiverAvatar = $('#receiverAvatar').val();
	var receiverName = $('#receiverName').val();*/
	
	CHAT_OBJ = {
		userTokenId:userTokenId,
		userTokenPswd:userTokenPswd,
		chatSig:chatSig,
		chatTimeStamp:chatTimeStamp,
		senderId:senderId,
		senderAvatar:senderAvatar,
		senderName:senderName,
		chatGroupId:chatGroupId,
		receiverId:chatGroupId,
		senderSerial:senderSerial
		/*receiverId:receiverId,
		receiverTokenId:receiverTokenId,
		receiverAvatar:receiverAvatar,
		receiverName:receiverName,*/
	};
	
	TEMPLATE_SELF = $('#template_self').html();
	Mustache.parse(TEMPLATE_SELF); 
	TEMPLATE_OTHER = $('#template_other').html();
	Mustache.parse(TEMPLATE_OTHER);
	
	var options = {
		userTokenId:userTokenId,
		userTokenPswd:userTokenPswd,
		senderId:senderId,
		chatGroupId:chatGroupId,
		receiverId:chatGroupId,
		chatSig:chatSig,
		chatTimeStamp:chatTimeStamp,
		senderSerial:senderSerial
	}
	
	var onJoinGroupFun = function(){
		sendSystemMsg(false, '欢迎'+senderName, 'msg_welcome');
	}
	var onLoginFun = function(){
		joinGroup(chatGroupId,onJoinGroupFun);
	}
	initCommonChat(options,onLoginFun,true);//isShowHour:true
}

function sendOffer(){
	if(!checkBail())return;//检查保证金
	if(HAVE_BEGUN == 1){
		lh.alert('本次拍卖正在预展中，请拍卖开始后开始竞价。');return;
	}
	if(IS_OVER || HAVE_BEGUN == 3){
		lh.alert('本次拍卖已经结束，感谢您的参与。');return;
	}
	var offerPrice = changePrice();
	CURRENT_PRICE = offerPrice;
	var chat = clone(CHAT_OBJ);
	chat.content = '出价'+offerPrice+'元';
	chat.price = offerPrice;
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = getHourMinute();
	chat.msgGroup = 'msg_price';
	chat.auctionGoodsId = CURRENT_AUCTION_GOODS.id;
	chat.localPrice = '出价<span style="color:green;"> '+offerPrice+'</span> 元';
	commonSendGroupMsg(chat);
	//修改最高价格和领先人
	changePriceGap();
	$('#currentPrice').text(offerPrice|| CURRENT_PRICE);
	$('#currentUser').text(USERNAME || '暂无');
	$('#offerPrice').val(offerPrice + PRICE_GAP);
	$('#offerTimes').text(++CURRENT_AUCTION_GOODS.offerTimes);
	//更新数据库
	var param = {
		offerPrice:CURRENT_PRICE, 
		offerTimes:CURRENT_AUCTION_GOODS.offerTimes,
		id:CURRENT_AUCTION_GOODS.id
	};
	updateAuctionGoods(param);
}

function sendMsg(msgContent,notDB,sender,msgGroup){
	var chat = clone(CHAT_OBJ);
	chat.content = msgContent || $("#msgContent").val();
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = getHourMinute();
	chat.msgGroup = msgGroup || 'msg_common';//普通消息
	if(sender)chat.senderName = sender;
	if(IS_HOST){
		sendSystemMsg(true, chat.content, 'msg_host', '主持人');
	}else{
		commonSendGroupMsg(chat,notDB);
	}
}

function sendSystemMsg(isRemoteSend, msgContent, msgGroup, senderName, bonus){
	if(!senderName)senderName = '系统';
	var sendHour = getHourMinute();
	if(isRemoteSend){
		var senderId = $('#senderId').val();
		var chat = {
			content:msgContent,
			chatGroupId:CHAT_OBJ.chatGroupId,
			senderAvatar:null,
			avatar:null,
			senderName:senderName,
			senderId:senderId,
			msgGroup:msgGroup,
			sendHour:sendHour,
			localPrice:null,
			price:null,
			agId:null,
			bonus:bonus
		};
		commonSendGroupMsg(chat,false,false);//:chat,notDB,notAppend
	}else{
		var chat = {msgGroup:msgGroup, sendHour:sendHour, senderName:senderName, content:msgContent};
		var rendered = Mustache.render(TEMPLATE_SELF, {chat:chat});
		commonGroupAppend(rendered);
	}
}

//TODO 主持人开始倒计时
function sendGroupMsgCountDown(){//发出开始拍卖倒计时消息，不显示出来，只刷新倒计时时间
	if(COUNT_DOWN_ING || TIMMER <= 20)return;
	COUNT_DOWN_ING = true;
	setRemainSeconds(CURRENT_AUCTION_GOODS.id);//更新倒计时
	var chat = clone(CHAT_OBJ);
	var senderId = $('#senderId').val();
	chat.myMsg = 'my_msg';
	chat.typeId = 2;
	chat.sendHour = getHourMinute();
	chat.msgGroup = 'count_down';//开始倒计时消息
	
	var chat = {
		content:'-sys-weipaike-countdown-begin-',
		chatGroupId:CHAT_OBJ.chatGroupId,
		senderAvatar:null,
		avatar:null,
		senderName:chat.senderName,
		senderId:senderId,
		msgGroup:chat.msgGroup,
		sendHour:chat.sendHour,
		localPrice:null,
		price:null,
		agId:CURRENT_AUCTION_GOODS.id,
		bonus:null
	};
	commonSendGroupMsg(chat,true,true);//:chat,notDB,notAppend
}

function updateAuctionGoods(param, isLoadNext){
	$.post('/updateAuctionQuickGoods', param, function(rsp){
		if(rsp.status == 'success' && rsp.remainSeconds){
			refreshTimmer(rsp.remainSeconds);
		}else{
			if(isLoadNext){//没有返回成功状态，返回了流拍或已完成竞拍，就加载下一个
				loadNextAuctionGoods();//next
			}
			if(!param.notShowTip){
				lh.alert(rsp.msg);
			}
		}
	}, 'json');
}

function auctionOneDone(){
	var param = {
		id:CURRENT_AUCTION_GOODS.id,
		done:1,
		notShowTip:1
	};
	updateAuctionGoods(param,true);
}

function auctionOver(){
	$('#have_begun_text').val('结束');
	var msgContent = '本次拍卖已经结束，感谢大家的参与，下一场拍卖即将开始。'
	sendSystemMsg(false, msgContent, 'msg_over', '主持人');
	IS_OVER = true;
	setTimeout(function(){
		location.reload();
	},5000);
}

function auctionPreCheck(auctionId){
	setTimeout(function(){
		$.post('/getAuctionQuickHaveBegun', {auctionId:auctionId}, function(rsp){
			if(rsp.status == 'success'){
				var haveBegun = rsp.haveBegun;
				if(haveBegun == 1){
					auctionPreCheck(auctionId);
				}else if(haveBegun == 2){
					HAVE_BEGUN = 2;
					$('#haveBegun').val(2);
					$('#have_begun_text').text('拍卖中');
					lh.alert('拍卖开始了，大家开始竞价吧。');
					loadNextAuctionGoods();
				}if(haveBegun == 3){
					auctionOver();
				}
			}
		}, 'json');
	},15000);//15秒
}

function getRemainSeconds(auctionGoodsId){
	if(!auctionGoodsId)return;
	$.post('/getAQGRemainSeconds', {AuctionQuickGoodsId:auctionGoodsId}, function(rsp){
		if(rsp.status == 'success'){
			TIMMER = rsp.remainSeconds;
			if(!TIMMER || TIMMER < 0)TIMMER = 120;
			var userCount = rsp.userCount;
			if(!userCount)userCount = 0;
			$('#onlineUser').text(userCount);
		}
	}, 'json');
}

function setRemainSeconds(auctionGoodsId){
	$.post('/setAQGRemainSeconds', {auctionGoodsId:auctionGoodsId}, function(rsp){
		COUNT_DOWN_ING = false;
		if(rsp.status == 'success'){
			getRemainSeconds(auctionGoodsId);//重新发请求，保证时间同步，减少误差
			//if(rsp.remainSeconds)TIMMER = rsp.remainSeconds;
		}
	}, 'json');
}

function addChat(chat){
	var param = {serial:chat.serial,chatGroupId:chat.chatGroupId,content:chat.content};
	$.post('/addChatQuick',param,function(rsp){
		if(rsp.status != 'success'){
			lh.alert(rsp.msg);
		}
	},'json');
}

CHECKING_FLAG = false;
function sendBonus(){
	if(CHECKING_FLAG)return;
	CHECKING_FLAG = true;
	$.post('/checkBonusRemain', null, function(rsp){
		frontLoginCheck(rsp);//登陆检查
		CHECKING_FLAG = false;
		if(rsp.status == 'success'){
			var username = rsp.username;
			var userId = rsp.userId;
			var msgContent = '['+username+'] 给大家发红包啦，点击这里抢红包。';
			sendSystemMsg(true, msgContent, 'msg_over', '主持人', userId);
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}

function receiveBonus(senderId){
	var param = {bossId:senderId,isGroupBonus:1};
	$.post('/receiveBonus', param, function(rsp){
		frontLoginCheck(rsp);//登陆检查
		if(rsp.status == 'success'){
			var money = rsp.money;
			var bonusId = rsp.bonusId;
			if(!money || !bonusId){
				lh.alert('红包已经被抢光了');return;
			}
			lh.alert('恭喜您成功抢到一个红包，金额为：'+money+'元，您可在个人中心的红包菜单里面查看详细信息');
		}else{
			lh.alert(rsp.msg);
		}
	},'json');
}
